import { Modal, Button, Checkbox, Form, Input, message } from 'antd'
import { useDispatch } from 'react-redux'
import { addRole, changeRole } from '@/store/actions/editrole'
import { useState } from 'react'
import { getRoleList } from '@/store/actions/roleManagement'

const EditRole = ({ editOpen, setEditOpen, isEdit, setIsEdit }) => {
  const [form] = Form.useForm()
  const dispatch = useDispatch()
  const [confirmLoading, setConfirmLoading] = useState(false)

  //编辑状态传内容
  if (isEdit) {
    form.setFieldsValue(isEdit)
  }

  const onOK = async () => {
    try {
      const data = await form.validateFields()
      setConfirmLoading(true)
      if (isEdit) {
        data.id = isEdit.id
        await dispatch(changeRole(data))
      } else {
        await dispatch(addRole(data))
      }
      setConfirmLoading(false)
      setEditOpen(false)
      dispatch(getRoleList({ page: 1, pagesize: 10 }))
      message.success('操作成功')
    } catch (e) {
      setConfirmLoading(false)
    }
  }
  const hideModal = () => {
    setEditOpen(false)
  }
  return (
    <Modal
      title={isEdit ? '编辑角色' : '新增角色'}
      open={editOpen}
      onOk={onOK}
      onCancel={hideModal}
      okText="确认"
      cancelText="取消"
      confirmLoading={confirmLoading}
      destroyOnClose
    >
      <Form
        name="basic"
        labelCol={{
          span: 6,
        }}
        wrapperCol={{
          span: 16,
        }}
        autoComplete="off"
        form={form}
        preserve={false}
      >
        <Form.Item
          label="角色名称"
          name="name"
          rules={[
            {
              required: true,
              message: '请输入角色名称',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="角色描述"
          name="description"
          rules={[
            {
              required: true,
              message: '请输入角色描述',
            },
          ]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default EditRole
